package com.huyun.web.concurrency.atomic;

import com.huyun.web.concurrency.annoations.ThreadSafe;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

@Slf4j
@ThreadSafe
public class AtomicExample5 {
    //AtomicIntegerFieldUpdater 原子性的更新某一个类的实例的指定的某一个字段
    //并且该字段由volatile进行修饰同时不能被static修饰
    //有些网上说而且不能被private修饰？下文将进行验证

    /*
     *  AtomicLong是作用是对长整形进行原子操作。而AtomicLongArray的作用则是对"
     *  长整形数组"进行原子操作,根据索引，对数据中的指定位置的数据进行院子性的更新
     */
    private static AtomicIntegerFieldUpdater<AtomicExample5> updater =
            AtomicIntegerFieldUpdater.newUpdater(AtomicExample5.class, "count");

    @Getter
    public volatile int count = 100;

    public static void main(String[] args) {

        AtomicExample5 example5 = new AtomicExample5();

        if (updater.compareAndSet(example5, 100, 120)) {
            log.info("update success 1, {}", example5.getCount());
        }

        if (updater.compareAndSet(example5, 100, 120)) {
            log.info("update success 2, {}", example5.getCount());
        } else {
            log.info("update failed, {}", example5.getCount());
        }
    }
}
